#include"myStdio.h"


FILE_* fopen_(const char* path,const char* mode)
{
    int flag = 0;
    int defaultMode = 0666;
    if(strcmp(mode,"r") == 0)
    {
        flag |= O_RDONLY;
    }
    else if(strcmp(mode,"w") == 0)
    {
        flag |= O_WRONLY | O_CREAT | O_TRUNC;
    }
    else if(strcmp(mode,"a") == 0)
    {
        flag |= O_WRONLY | O_CREAT | O_APPEND;
    }
    else
    {
        //TODO
    }
    int fd = 0;

    if(flag & O_RDONLY) fd = open(path,flag);
    else fd = open(path,flag,defaultMode);
    if(fd < 0)
    {
        const char* err = strerror(errno);
        write(2,err,strlen(err));
        return NULL;//为什么打开文件失败会返回NULL
    }

    FILE_* fp = (FILE_*)malloc(sizeof(FILE_));
    assert(fp);
    fp->_flags = SYNC_LINE;//默认行刷新
    fp->_fileno = fd;
    fp->_cap = SIZE;
    fp->_size = 0;
    memset(fp->_buffer,0,SIZE);

    return fp;//这就是为什么打开一个文件，就会返回一个FILE*指针
}

int fwrite_(const void* ptr,int num,FILE_* fp)
{
    //1.写入到缓冲区中
    memcpy(fp->_buffer+fp->_size,ptr,num);//这里不考虑缓冲区溢出问题
    fp->_size += num;

    //2.判断是否刷新
    if(fp->_flags & SYNC_NOW)
    {
        write(fp->_fileno,fp->_buffer,fp->_size);
        fp->_size = 0;//清空缓冲区
    }
    else if(fp->_flags & SYNC_FULL)
    {
        if(fp->_cap == fp->_size)
        {
            write(fp->_fileno,fp->_buffer,fp->_size);
            fp->_size = 0;
        }
    }
    else if(fp->_flags & SYNC_LINE)
    {
        if(fp->_buffer[fp->_size-1] == '\n')//不考虑abc\nab
        {
            write(fp->_fileno,fp->_buffer,fp->_size);
            fp->_size = 0;
        }
    }
    else
    {
        //TODO
    }
}

void fflush_(FILE_* fp)
{
    if(fp->_size > 0) write(fp->_fileno,fp->_buffer,fp->_size);
    fsync(fp->_fileno);//将数据，强制要求OS进行外设刷新！
    fp->_size = 0;
}

void fclose_(FILE_* fp)
{
    //先刷新再关闭
    fflush_(fp);
    close(fp->_fileno);
}

//无论是fwrite或者是write本质其实都是拷贝函数！！(拷贝到缓冲区)



